package com.edol.painting.main;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.signature.StringSignature;
import com.doodle.common.utils.Future;
import com.doodle.common.utils.FutureListener;
import com.doodle.common.utils.JobLimiter;
import com.doodle.common.utils.ThreadPool;
import com.edol.painting.PainterConfig;
import com.edol.painting.R;
import com.edol.painting.data.PaintingDatabase;
import com.edol.painting.utils.BitmapUtils2;
import com.edol.painting.utils.Constant;
import com.edol.painting.widget.ProgressHUD;

import java.io.File;

/*  =======================================================================================
 *  Copyright (C) 2017 dlboard.com. All rights reserved.
 *
 *  This computer program source code file is protected by copyright law and international
 *  treaties. Unauthorized distribution of source code files, programs, or portion of the
 *  package, may result in severe civil and criminal penalties, and will be prosecuted to
 *  the maximum extent under the law.
 *
 *  ---------------------------------------------------------------------------------------
 * Author:Administrator
 * Date:2017/7/19
 * Desc:
 *
 * ======================================================================================== */

public class ShareQrcodeActivity extends FragmentActivity implements View.OnClickListener {
    private ImageView mQrcodeView;
    private TextView mTipsView;
    private TextView mDownloadUrlTv;
    private View mLayQrcode;

    private boolean setViewHeight = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share_qrcode);

        mLayQrcode = findViewById(R.id.lay_qrcode);
        mQrcodeView = (ImageView) findViewById(R.id.qrcode_img);
        mDownloadUrlTv = (TextView) findViewById(R.id.qrcode_download_url);
        mTipsView = (TextView) findViewById(R.id.qrcode_tips);


        findViewById(R.id.save_btn).setOnClickListener(this);
        findViewById(R.id.share_btn).setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);

        String appName = getString(R.string.app_name);
        mTipsView.setText(getString(R.string.share_qr_code_tips, appName));
        Glide.with(this)
                .load(PainterConfig.PGYER_QRCODE_URL)
                .into(mQrcodeView);

        Glide.with(this)
                .load(PainterConfig.PGYER_QRCODE_URL)
                .animate(R.anim.img_load_fade)
                .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
                .into(getImgViewTarget(mQrcodeView));
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus && setViewHeight) {
            setViewHeight = false;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /*case R.id.left_image:
                finish();
                break;*/
            case R.id.save_btn:
                //保存到本地
                savePicture();
                break;
            case R.id.share_btn:
                sharePicture();
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    private GlideDrawableImageViewTarget getImgViewTarget(final ImageView imgView) {
        return new GlideDrawableImageViewTarget(imgView) {
            @Override
            public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                super.onResourceReady(resource, animation);
                if (resource instanceof GlideBitmapDrawable) {
                    Bitmap bmp = ((GlideBitmapDrawable) resource).getBitmap();
                    imgView.setVisibility(View.VISIBLE);
                    mDownloadUrlTv.setVisibility(View.INVISIBLE);
                    mTipsView.setVisibility(View.VISIBLE);
                    imgView.setImageBitmap(bmp);
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                imgView.setVisibility(View.INVISIBLE);
                mDownloadUrlTv.setVisibility(View.VISIBLE);
                mTipsView.setVisibility(View.GONE);

                String webLinkText = "<a href='" + PainterConfig.PGYER_DOWNLOAD_URL + "'>二维码图片显示失败，点击跳转到下载页面</a>";
                mDownloadUrlTv.setText(Html.fromHtml(webLinkText));
                mDownloadUrlTv.setMovementMethod(LinkMovementMethod.getInstance());
            }
        };
    }

    private void sharePicture() {
        mLayQrcode.setDrawingCacheEnabled(true);
        Bitmap bm = mLayQrcode.getDrawingCache();
        final Bitmap bmp = bm.createBitmap(bm);
        mLayQrcode.setDrawingCacheEnabled(false);
        final ProgressHUD progressHUD = ProgressHUD.create(this);
        progressHUD.show();

        new JobLimiter(ThreadPool.getInstance(), 1).submit(new ThreadPool.Job<String>() {
            @Override
            public String run(ThreadPool.JobContext jc) {
                String destPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constant.PAINTINGS_DIR + "qrcode.jpeg";
                BitmapUtils2.saveImage(bmp, destPath, 100, true);
                return destPath;
            }
        }, new FutureListener<String>() {
            @Override
            public void onFutureDone(final Future<String> future) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressHUD.dismiss();
                        PaintingDatabase.getInstance().sharePainting(ShareQrcodeActivity.this, future.get());
                    }
                });
            }
        });
    }


    private void savePicture() {
        mLayQrcode.setDrawingCacheEnabled(true);
        Bitmap bm = mLayQrcode.getDrawingCache();
        bm = bm.createBitmap(bm);
        mLayQrcode.setDrawingCacheEnabled(false);
        if (bm != null) {
            String fileName = new StringBuilder("easy_doodle_")
                    .append(System.currentTimeMillis())
                    .append(".png")
                    .toString();

            toSave(bm, fileName);
        }
    }


    private void toSave(Bitmap bitmap, String fileName) {
        File fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (BitmapUtils2.savePngImageToGallery(this, bitmap, fileDir, fileName, 100, true)) {
            String tips = getString(R.string.save_picture_ok_tips,
                    fileDir.getAbsolutePath(),
                    fileName);
            Toast.makeText(this, tips, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,
                    getString(R.string.save_picture_error_tips),
                    Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
